package com.quan.api.wx.pay;


import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.quan.commons.core.bean.R;
import com.quan.commons.core.biz.support.MyBaseController;
import com.quan.commons.core.configuration.WxPayConfiguration;
import com.quan.commons.core.properties.SystemValueProperties;
import com.quan.commons.core.properties.WxPayProperties;
import com.quan.commons.core.utils.IpHelper;
import com.quan.mall.commons.constant.MallRabbitMQConstant;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.time.LocalDateTime;

/**
 * 微信支付
 * 商场商品订单支付
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/api/wx/order/pay/{appId}")
public class WxOrderPayController extends MyBaseController {

	@Autowired
	private SystemValueProperties props;
	
	@Autowired
	private RabbitTemplate rabbitTemplate;
	
	/**
	 * 预支付交易会话标识
	 * 
	 * @param unifiedOrderRequest
	 * @return
	 */
	@PostMapping(value = "now")
	public Object pay(@PathVariable String appId, @RequestBody WxPayUnifiedOrderRequest unifiedOrderRequest) {
		try {
			final WxPayService wxPayService = WxPayConfiguration.getPayService(appId);
			final WxPayProperties.Config config = WxPayConfiguration.getAppIdConfig(appId);

			log.info("========================>微信支付<========================");
			log.info("==>微信支付商户名：{}", config.getName());
			log.info("==>微信支付商户号：{}", config.getMchId());
			log.info("==>发起时间：{}", LocalDateTime.now());

			final String notifyUrl = this.props.getWechat().getOrderPayNotifyUrl();
			unifiedOrderRequest.setSpbillCreateIp(IpHelper.getIpAddr(request));
			unifiedOrderRequest.setNotifyUrl(notifyUrl.replace("{appId}", appId));
			unifiedOrderRequest.setTradeType(WxPayConstants.TradeType.JSAPI);

			Object createOrder = wxPayService.createOrder(unifiedOrderRequest);
			log.info("==>创建”预支付交易会话标识“成功，等待用户支付");
			
			return R.ok().put("data", createOrder);

		} catch (Exception e) {
			log.error("==>创建”预支付交易会话标识“失败，错误信息：{}", e.getMessage());
		}
		return R.failure("微信支付：创建”预支付交易会话标识“失败");
	}

	/**
	 * 支付回调通知处理
	 * 
	 * @param xmlData
	 * @return
	 * @throws WxPayException
	 * @throws ParseException
	 */
	@PostMapping("notify")
	public String parseOrderNotifyResult(@RequestBody String xmlData, @PathVariable String appId) throws WxPayException, ParseException {
		log.info("==>微信支付，回调通知，业务处理发送给队列");

		final WxPayService wxPayService = WxPayConfiguration.getPayService(appId);

		WxPayOrderNotifyResult notifyResult = wxPayService.parseOrderNotifyResult(xmlData);

		// RabbitMQ 消息队列处理支付回调
		this.rabbitTemplate.convertAndSend(
				MallRabbitMQConstant.MALL_EVENT_EXCHANGE,
				MallRabbitMQConstant.MALL_ROUTING_KEY_PAY_NOTITY,
				notifyResult);


		return WxPayNotifyResponse.success("成功");
	}

}
